Data exploration is not only about creating numbers and summary statistics. Sometimes a good plot can reveal more insights than a whole dataframe filled with numbers (especially to the human eye). In this exercise we make use of what we’ve just learned about plots with ggplot2. This time we are going to use all of the Gapminder GDP data.
filter() function for choosing the individual time periods, so you need to exclude that line from the previous exercises here.
In the previous exercises we only analyzed how the period from 1960 to 1969 compares to the period from 2002 to 2011. The nice thing about plots is that we can make use of the whole range of years and still identify differences between various periods. Our plot of choice, therefore, is a line plot to create a nice time series.
geom_point as in the slides, the name of the geom we need is geom_line. In addition, in the aesthetics definition aes() you should define a grouping variable group = 1. Otherwise, ggplot assumes that you want to plot one line for each year.
Admittedly, this may not be the best approach to identify differences between the periods directly. We don’t know when our periods start and when they end. Luckily, this can be done at least two different ways. Let’s start with the first one: using colors for different periods. For this purpose, we need an indicator variable as a grouping variable, so that we can use different colors for the line at each period.
mutate() and the if_else lets you create the new variables we need. To get some sensible legend labels later you should specify the indicator variables as strings.
After we’re set up with our indicator variable, it’s plotting time again. We can simply reuse our code from before and define a grouping color in the aesthetics definition.
aes(), you can choose the option color = indicator_variable to define the grouping.
Now we can see some visual differences between the different periods. One last thing, however, is that there are way too many labels on the x-axis. Maybe a more sensible axis labeling approach would be to create axis breaks for every ten years steps.
scale_x_discrete() and its breaks with the option breaks = breaks_vector.